package com.gouaixin.bee.beeframework2.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.WindowManager;

import com.gouaixin.bee.beeframework2.tool.mLog;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.gouaixin.bee.beeframework2.MyAPI;
import com.gouaixin.bee.beeframework2.R;
import com.gouaixin.bee.beeframework2.activity.C1_LiaotianJiemianTestActivity;
import com.gouaixin.bee.beeframework2.activity.C2_ServiceMsgActivity;
import com.gouaixin.bee.beeframework2.activity.JiqiMessadialogActivity;
import com.gouaixin.bee.beeframework2.activity.MyMainActivity;
import com.gouaixin.bee.beeframework2.extra.im.ChatData;
import com.gouaixin.bee.beeframework2.bean.getMessageResponse;
import com.gouaixin.bee.beeframework2.model.EncodeIdModel;
import com.gouaixin.bee.beeframework2.model.ServiceChatModel;
import com.gouaixin.bee.beeframework2.tool.PreferencesUtils;
import com.gouaixin.bee.beeframework2.bean.BaseModel;
import com.lidroid.xutils.http.RequestParams;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.bmob.im.BmobNotifyManager;

/**
 * Created by Administrator on 2015/4/2.
 */
public class MyService extends Service {
    String TAG = "Demo";
    int tempMsg = -1;


    String jname = "";//推送消息中的女生姓名
    String jid = "";//推送消息中的女生id
    String serviceId = "";//相关联的红娘id
    String serviceMsg = "";//推送的消息
//    MediaPlayer mediaPlayer;

    Context context = MyService.this;
    int liaoStatus;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        Log.e("Demo", "后台服务：onCreate");


//        mediaPlayer = MediaPlayer.create(this, R.raw.test);

        /*
         * 要用MediaPlayer来创建，不能用MediaPlayer的对象来创建 // 不用带后缀 mediaPlayer = new
         * MediaPlayer(); mediaPlayer.create(this, R.raw.test);
         */

        /*
         * try { mediaPlayer.setDataSource("/sdcard/music/lost times.mp3");
         * mediaPlayer.prepare();
         *
         *
         * //方法二，从网上的链接获取歌曲 try { mediaPlayer.setDataSource(
         * "http://www.yousss.com/uploadfile/mp3/2007-11/20071129134414713.mp3"
         * );
         */

        // mediaPlayer.setLooping(true);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("Demo", "后台服务：onStartCommand");

        boolean haveInit = PreferencesUtils.getBoolean(context, "haveInit", false);
        long initTime = PreferencesUtils.getLong(context, "initTime", 0);

//        if(haveInit==false){
        initJnameAndJid();
        PreferencesUtils.putBoolean(context, "haveInit", true);

//        }
        return super.onStartCommand(intent, flags, startId);

    }


    private Runnable mRunnable = new Runnable() {
        public void run() {
            // 更新界面
            mHandler.obtainMessage().sendToTarget();
            // 每1秒钟执行一次
            mHandler.postDelayed(mRunnable, 1000);
        }

    };
    long jiangeTime;

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            // 此处可以更新UI界面
            long initTime = PreferencesUtils.getLong(context, "initTime", 0);
            long currentTime = System.currentTimeMillis();
            jiangeTime = (currentTime - initTime) / 1000;
            mLog.e("当前间隔时间：" + jiangeTime + "秒");
//            if(jiangeTime%(30)==0){
//                initData();
//            }

            isNoMerber();

        }

    };

    String HerGender = "2";//传出对象的性别


    private void initData() {

        /***
         * liaoStatus（聊天状态）：0（程序在后台）；1（程序在前端显示，非聊天界面）；2（显示聊天界面）
         */
//        liaoStatus = PreferencesUtils.getInt(context, "liaoStatus");
//        mLogUtil.e("当前的聊天状态：liaoStatus=" + liaoStatus+"currentTime="+System.currentTimeMillis());


//        switch (liaoStatus) {
//            case 0:
////                getJiqiren();
//                break;
//
//            case 1:
//
//                break;
//
//            case 2:
//                break;
//        }

//        //会员类型判断
//        BmobQuery<USER> query = new BmobQuery<USER>();
//        query.getObject(context, BmobUser.getCurrentUser(context).getObjectId(), new GetListener<USER>() {
//            @Override
//            public void onSuccess(USER user) {
//                mLogUtil.e("消息推送时，进行会员类型判断：");
//                //不是会员时的推送机制
////                if (user.getBaoyueType() == 0 && user.getYbiType() == 0 && user.getVipType() == 0 && user.getAbiType() == 0 && user.getHongniangType() == 0) {
//                    mLogUtil.e("什么都没开通,消息推送：");
//                    isNoMerber();
////                }
//
//
//            }
//
//            @Override
//            public void onFailure(int i, String s) {
//
//            }
//        });

//        MemberModel.haveRecharge(context,new MemberModel.HaveRechargeListener() {
//            @Override
//            public void onResult(boolean haveRecharge) {
//                if(haveRecharge==false){
//                    Log.e("Demo","没开通会员");
//                    isNoMerber();
//                }else{
//                    Log.e("Demo","开通了会员");
//                }
//            }
//        });


    }

    private void initJnameAndJid() {
        ServiceChatModel.getJName(context, new ServiceChatModel.CallbackLister() {

            @Override
            public void onSuccess(String name, String id) {
                jname = name;
                jid = EncodeIdModel.encodeId(id);
                serviceId = EncodeIdModel.decodeServiceId(jid);
                // 通过Handler启动线程
                mHandler.post(mRunnable);
            }
        });

    }

    /**
     * 不是会员时的推送机制
     * 1.
     */
    private void isNoMerber() {
//        Log.e("Demo", "后台服务：isNoMerber：tempMsg=" + tempMsg);

        long push_time = 20*60;//秒为单位

        if (jiangeTime == push_time) {
            Log.e("Demo", "发送第1条消息");
            send(0);
        } else if (jiangeTime == push_time * 2) {
            Log.e("Demo", "发送第2条消息");
            send(1);
        } else if (jiangeTime == push_time * 3) {
            Log.e("Demo", "发送第3条消息");
            send(2);
        } else if (jiangeTime == push_time * 4) {
            Log.e("Demo", "发送第4条消息");
            send(3);
        } else {
            Log.e("Demo", "后台服务：isNoMerber：干掉自己，消息发送完毕");
        }
    }

    /**
     * 不是会员时的推送机制
     * 1.
     */
    private void send(int tempMsg) {

        if (tempMsg == 0) {

            serviceMsg = getResources().getString(R.string.hongniang_01);
            serviceMsg = serviceMsg.replace("xxx", jname);
            serviceMsg = serviceMsg.replace("yyy", serviceId);
            serviceMsg = serviceMsg.replace("zzz", jid);
            Log.e("test", "后台服务：isNoMerber：发送消息01=" + serviceMsg);
            ServiceChatModel.receiveServiceMsg(context, serviceMsg);
            tempMsg++;

            showNotifycation();

        } else if (tempMsg == 1) {

            serviceMsg = getResources().getString(R.string.hongniang_02);
            serviceMsg = serviceMsg.replace("xxx", jname);
            serviceMsg = serviceMsg.replace("yyy", serviceId);
            serviceMsg = serviceMsg.replace("zzz", jid);
            Log.e("test", "后台服务：isNoMerber：发送消息02=" + serviceMsg);
            ServiceChatModel.receiveServiceMsg(context, serviceMsg);
            tempMsg++;

            showNotifycation();
        } else if (tempMsg == 2) {

            serviceMsg = getResources().getString(R.string.hongniang_03);
            serviceMsg = serviceMsg.replace("xxx", jname);
            serviceMsg = serviceMsg.replace("yyy", serviceId);
            serviceMsg = serviceMsg.replace("zzz", jid);
            Log.e("test", "后台服务：isNoMerber：发送消息03=" + serviceMsg);
            ServiceChatModel.receiveServiceMsg(context, serviceMsg);
            tempMsg++;

            showNotifycation();
        } else if (tempMsg == 3) {

            serviceMsg = getResources().getString(R.string.hongniang_04);
            serviceMsg = serviceMsg.replace("xxx", jname);
            serviceMsg = serviceMsg.replace("yyy", serviceId);
            serviceMsg = serviceMsg.replace("zzz", jid);
            Log.e("test", "后台服务：isNoMerber：发送消息04=" + serviceMsg);
            ServiceChatModel.receiveServiceMsg(context, serviceMsg);
            tempMsg++;

            showNotifycation();
        } else {
            Log.e("test", "后台服务：isNoMerber：干掉自己，消息发送完毕");

        }
    }


    private static WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams();

    public static WindowManager.LayoutParams getMywmParams() {
        return wmParams;
    }

    private void showNotifycation() {
        Intent it = new Intent().setClass(context, C2_ServiceMsgActivity.class);
        String tickerText = "51约爱给您发了条消息";
        String contentTitle = "51红娘";
        String contentText = "系统红娘给您发了条消息。";
        BmobNotifyManager.getInstance(context).showNotifyWithExtras(true, true, R.drawable.mylogo, tickerText, contentTitle, contentText, it);
    }

    String id = "";
    String name = "";
    String myGender = "";
    String icon = "";
    String qianming = "";
    String msg = "";
    String time = "";
    String cid = "";
    Bitmap iconBitmap;
    Intent pit;

    /**
     * 1.随即得到一个机器人的昵称和id
     * 2.随机得到一条消息
     * 3.用机器人给当前用户发消息
     * 4.弹出对话卡框
     */
    private void getJiqiren() {
        String mGender = PreferencesUtils.getString(context, "gender", "男");
        cid = PreferencesUtils.getString(context, "id", "");

        mLog.e("mGender=" + mGender);

        if (mGender.equals("男")) {
            HerGender = "2";//获取女生
        } else {
            HerGender = "1";//获取男生
        }

        if (mGender.equals("男")) {
            myGender = "1";//获取女生
        } else {
            myGender = "2";//获取男生
        }

        BaseModel.setCallBackLister(new BaseModel.CallBackLister() {
            @Override
            public String onCallBack(String url, String data) {

                try {
                    JSONArray jsonArray = new JSONArray(data);
                    JSONObject jsonOb = (JSONObject) jsonArray.opt(0);
                    id = jsonOb.getString("id");
                    name = jsonOb.getString("name");
                    icon = jsonOb.getString("icon");
                    qianming = jsonOb.getString("qianming");
                    getMessage();
                } catch (Exception e) {
                    mLog.e(e.getMessage());
                    e.printStackTrace();
                }
                return url;
            }
        });

        RequestParams params = new RequestParams();
        params.addBodyParameter("tuijian", "1");//1.推荐，0.最新
        params.addBodyParameter("Gender", HerGender);//1.男，2.女
        BaseModel.post(MyAPI.friends, params);
    }

    /**
     * 获取随机消息
     */
    private void getMessage() {

        BaseModel.setCallBackLister(new BaseModel.CallBackLister() {
            @Override
            public String onCallBack(String url, String data) {

                try {
                    getMessageResponse obj = new Gson().fromJson(data, getMessageResponse.class);

                    msg = obj.getMessage();
                    mLog.e("随机获取语言库：msg=" + msg);

                    //将聊天记录保存到网络
                    addChatFriend();

                    //将聊天记录保存到本地
                    saveMessage();

                    /***
                     * 准备预置意图
                     */
                    Intent pit = new Intent().setClass(context, C1_LiaotianJiemianTestActivity.class);
                    pit.putExtra("id", id);
                    pit.putExtra("name", name);
                    pit.putExtra("icon", icon);
                    pit.putExtra("qianming", qianming);
                    pit.putExtra("flag", "0");

                    switch (liaoStatus) {
                        case 0:
                            //发送消息、弹出对话框
                            senMessage();
                            BmobNotifyManager.getInstance(context).showNotifyWithExtras(true, true, R.drawable.mylogo, name + "给您发了条消息", name, msg, pit);
                            break;
                        case 1:
                            BmobNotifyManager.getInstance(context).showNotifyWithExtras(true, true, R.drawable.mylogo, name + "给您发了条消息", name, msg, pit);
                            break;
                    }


                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                    mLog.e("随机获取语言库：出错：" + e.getMessage());
                }
                return url;
            }
        });

        RequestParams params = new RequestParams();
        params.addBodyParameter("cishu", "1");//1.推荐，0.最新
        params.addBodyParameter("Gender", myGender);//1.男，2.女
        BaseModel.post(MyAPI.getmessage, params);

    }

    /**
     * 弹出消息通知栏
     */
    //通知管理器
    private NotificationManager nm;
    //通知显示内容
    private PendingIntent pd;

    int temp = 1;

    private void showNotification() {
        //初始化通知管理者
        nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Intent pit = new Intent(context, MyMainActivity.class);
        /***
         * 准备预置意图
         */
        pit = new Intent().setClass(context, C1_LiaotianJiemianTestActivity.class);
        pit.putExtra("id", id);
        pit.putExtra("name", name);
        pit.putExtra("icon", icon);
        pit.putExtra("qianming", qianming);
        pit.putExtra("flag", "0");
        pd = PendingIntent.getActivity(context, 0, pit, 0);

//        Notification noti = new Notification.Builder(context)
//
//                .setContentIntent(pd)
//                .setTicker(name+"给您发了条消息")
//                .setContentTitle(name)
//                .setContentText(msg)
////                .setSmallIcon(R.drawable.new_mail)
//                .setLargeIcon(iconBitmap)
//                .build();
//
//
//        nm.notify(temp++, noti);


        Notification baseNF = new Notification();


//设置通知在状态栏显示的图标


        baseNF.icon = R.drawable.mylogo;


//通知时在状态栏显示的内容

        baseNF.tickerText = name + "给您发了条消息";


//通知的默认参数 DEFAULT_SOUND, DEFAULT_VIBRATE, DEFAULT_LIGHTS.

//如果要全部采用默认值, 用 DEFAULT_ALL.

//此处采用默认声音

        baseNF.defaults = R.raw.notify;

        baseNF.defaults = Notification.DEFAULT_VIBRATE;

        baseNF.defaults = Notification.DEFAULT_LIGHTS;


//让声音、振动无限循环，直到用户响应

        baseNF.flags = Notification.FLAG_INSISTENT;


//通知被点击后，自动消失

        baseNF.flags = Notification.FLAG_AUTO_CANCEL;


//点击'Clear'时，不清楚该通知(QQ的通知无法清除，就是用的这个)

        baseNF.flags |= Notification.FLAG_NO_CLEAR;


//第二个参数 ：下拉状态栏时显示的消息标题 expanded message title

//第三个参数：下拉状态栏时显示的消息内容 expanded message text

//第四个参数：点击该通知时执行页面跳转

        baseNF.setLatestEventInfo(context, name, msg, pd);


//发出状态栏通知

//The first parameter is the unique ID for the Notification

// and the second is the Notification object.

        nm.notify(temp++, baseNF);


//        //定义NotificationManager
//        String ns = Context.NOTIFICATION_SERVICE;
//        NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
//        //定义通知栏展现的内容信息
//        int icon = R.drawable.mylogo;
//        CharSequence tickerText = "您有新的消息，请注意查收";
//        long when = System.currentTimeMillis();
//        Notification notification = new Notification(icon, tickerText, when);
//
//        //定义下拉通知栏时要展现的内容信息
//        Context context = getApplicationContext();
//        CharSequence contentTitle = name;
//        CharSequence contentText = msg;
//        Intent notificationIntent = new Intent(this, MyMainActivity.class);
//        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
//                notificationIntent, 0);
//        notification.setLatestEventInfo(context, contentTitle, contentText,
//                contentIntent);
//
//        //用mNotificationManager的notify方法通知用户生成标题栏消息通知
//        mNotificationManager.notify(1, notification);

    }

    /**
     * 将聊天消息保存到本地聊天列表
     */
    private void saveMessage() {
        mLog.e("恢复运行时读取的聊天记录：");
        String dataStr = PreferencesUtils.getString(context, id + "liao", "");
        ArrayList<ChatData> datas = new ArrayList<ChatData>();

        if (dataStr != null && !dataStr.equals("")) {
            Gson gson = new Gson();

            List<ChatData> ps = gson.fromJson(dataStr, new TypeToken<List<ChatData>>() {
            }.getType());
            mLog.e("恢复运行时读取的聊天记录：tostring=" + ps.toString());
            datas = (ArrayList<ChatData>) ps;

            for (int i = 0; i < ps.size(); i++) {
                ChatData p = ps.get(i);
                mLog.e("恢复运行时读取的聊天记录：content=" + p.getContent());
            }
        }


        String content_str;
        content_str = msg;
        String dropk = content_str.replace(" ", "");
        String droph = dropk.replace("\n", "");
        ChatData chatData;
        time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        chatData = new ChatData(content_str, ChatData.RECEIVER, time);
        datas.add(chatData);


        String str = new Gson().toJson(datas);
        mLog.e("暂停时保存的聊天记录：" + id + "liao=" + str);
        PreferencesUtils.putString(context, id + "liao", str);


    }

    private void addChatFriend() {

        BaseModel.setCallBackLister(new BaseModel.CallBackLister() {
            @Override
            public String onCallBack(String url, String data) {


                return url;
            }
        });

        RequestParams params = new RequestParams();
        params.addBodyParameter("id", id);
        params.addBodyParameter("cid", cid);
        params.addBodyParameter("text", msg);
        params.addBodyParameter("time", time);
        BaseModel.post(MyAPI.addchatfriend, params);
    }

    /**
     * 用机器人给当前用户发消息
     * 1.将聊天消息保存到本地聊天列表
     * 2.弹出对话框（显示icon、name和msg），当用户点击聊天界面时，跳转到聊天界面
     */
    private void senMessage() {
        Intent it = new Intent().setClass(context, JiqiMessadialogActivity.class);
        it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        it.putExtra("id", id);
        it.putExtra("name", name);
        it.putExtra("icon", icon);
        it.putExtra("qianming", qianming);
        it.putExtra("text", msg);
        startActivity(it);
    }


    /**
     * 用系统机器人给当前用户发消息
     * 1.将聊天消息保存到本地聊天列表
     * 2.弹出对话框（显示icon、name和msg），当用户点击聊天界面时，跳转到聊天界面
     */
    private void sendServiceMessage(String text) {
        Intent it = new Intent().setClass(context, JiqiMessadialogActivity.class);
        it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        it.putExtra("id", id);
        it.putExtra("name", name);
        it.putExtra("icon", "isServiceIcon");
        it.putExtra("qianming", qianming);
        it.putExtra("text", text);
        startActivity(it);
    }


    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);

        mLog.e("后台服务：onStart");
        /*
         * //可以在OnCreate里面创建与音乐的链接，也可以在OnStart里面创建 mediaPlayer =
         * MediaPlayer.create(this, R.raw.test);
         */
//        Toast.makeText(this, "Play Service onStart", Toast.LENGTH_LONG).show();
        Log.e(TAG, "ServiceonStart");
//        mediaPlayer.start();
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();

        mLog.e("后台服务：onDestroy");
        Intent localIntent = new Intent();
        localIntent.setClass(this, MyService.class);  //销毁时重新启动Service
        this.startService(localIntent);


//        mediaPlayer.stop();
    }


}
